<style></style>
<template>
  <div>
    <!-- 头部搜索区 -->
    <div style="margin-bottom: 10px;">
      <span>车位编号：</span>
      <el-input v-model="searchText" style="width: 240px;margin-right: 10px;" placeholder="请输入房产名称" />
      <span>状态：</span>
      <el-radio-group v-model="searchState" class="ml-4">
        <el-radio :value="2" size="large" :checked="true">全部</el-radio>
        <el-radio :value="0" size="large">租凭</el-radio>
        <el-radio :value="1" size="large">买</el-radio>
      </el-radio-group>
      <el-button :icon="Search" type="primary" @click="btnSearch()" plain style="margin-left: 10px;">查询</el-button>
      <el-button @click="btnAdd()" type="success" plain><el-icon>
          <Plus />
        </el-icon>添加</el-button>
    </div>
    <!-- 表格数据展示区 -->
    <div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="车位使用编号" prop="Useid" />
        <el-table-column label="车位编号" prop="Pnumber" />
        <el-table-column label="车位所有人" prop="Orealname" />
        <el-table-column label="使用性质" prop="Usetype">
          <template #default="scope">
            <el-tag :type="scope.row.Usetype ? 'primary' : 'success'">{{ scope.row.Usetype ? "买" : "租凭"
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="费用" prop="Useprice" />
        <el-table-column label="开始时间" prop="Usestarttime" width="200px">
          <template #default="scope">
            <span>{{ convertDateTime(scope.row.Usestarttime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" prop="Useendtime" width="200px">
          <template #default="scope">
            <span>{{ convertDateTime(scope.row.Useendtime) }}</span>
          </template>
        </el-table-column>


        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" :icon="Edit" type="warning" plain
              @click="handleEdit(scope.$index, scope.row)"></el-button>
            <el-button size="small" :icon="Delete" type="danger" plain
              @click="handleDelete(scope.$index, scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <el-config-provider :locale="locale">
      <div class="demo-pagination-block" style="margin-top: 10px;">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50, 100]" :small="small" :disabled="disabled" :background="background"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-config-provider>
  </div>


  <!-- 添加/编辑 -->
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" :destroy-on-close="true"
    :before-close="clearForm">
    <el-form :model="formDate" :rules="rules" ref="ruleFormRef">
      <el-form-item label="车位编号" :label-width="formLabelWidth" prop="Pid">
        <el-select v-model="formDate.Pid" clearable placeholder="请选择车位编号" style="width: 330px">
          <el-option v-for="item in parkingList" :key="item.Pid" :label="item.Pname" :value="item.Pid"
            :disabled="item.Pstate" />
        </el-select>
      </el-form-item>

      <el-form-item label="车位所有人" :label-width="formLabelWidth" prop="Oid">
        <el-select v-model="formDate.Oid" clearable placeholder="请选择车所有人" style="width: 330px">
          <el-option v-for="item in ownerList" :key="item.Oid" :label="item.Orealname" :value="item.Oid" />
        </el-select>
      </el-form-item>

      <el-form-item label="车位价格" :label-width="formLabelWidth" prop="Priceid">
        <el-select v-model="formDate.Priceid" clearable placeholder="请选择车位价格" style="width: 330px">
          <el-option v-for="item in parkingPriceList" :key="item.Priceid" :label="item.PriceInfo"
            :value="item.Priceid" />
        </el-select>
      </el-form-item>
      <el-config-provider :locale="locale">
        <el-form-item label="开始时间" :label-width="formLabelWidth" prop="Usestarttime">
          <div class="block">
            <el-date-picker v-model="formDate.Usestarttime" type="datetime" placeholder="请选择开始时间"
              style="width: 330px" />
          </div>
        </el-form-item>
        <el-form-item label="结束时间" :label-width="formLabelWidth" prop="Useendtime">
          <div class="block">
            <el-date-picker v-model="formDate.Useendtime" type="datetime" placeholder="请选择结束时间" style="width: 330px" />
          </div>
        </el-form-item>
      </el-config-provider>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="btnSave(ruleFormRef)">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, onMounted, reactive, markRaw } from 'vue'
import { Search, Delete, Edit } from '@element-plus/icons-vue'
import axios from 'axios'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { ElMessage, ElMessageBox, FormRules, FormInstance } from 'element-plus'

//存储表格数据信息
let tableData = ref([]);

//搜索信息
var searchText = ref("");

//条件查询状态
var searchState = ref(2);

//设置分页中文显示
const locale = ref(zhCn)


//页码数
const currentPage = ref(1)
//页条数
const pageSize = ref(5)
//总条数
var total = ref(0)

//控制打开/关闭模态框
const dialogFormVisible = ref(false)
//表单输入框前标题宽度
const formLabelWidth = '100px'

//弹出层标题
var dialogTitle = ref("")
//表单信息
var formDate = ref({
  "Useid": 0,
  "Createtime": null,
  "Isdelete": false,
  "Oid": null,
  "Pid": null,
  "Priceid": null,
  "Useendtime": "",
  "Usestarttime": ""
})

//存储车位信息下拉框数据
var parkingList = ref([])
//车位价格信息
var parkingPriceList = ref([])
//业主信息
var ownerList = ref([])

//切换页条数
const handleSizeChange = (val) => {
  bindData(currentPage.value, val, searchState.value, searchText.value)
}

//切换页数
const handleCurrentChange = (val) => {
  bindData(val, pageSize.value, searchState.value, searchText.value)
}

//组件加载完毕后执行
onMounted(() => {
  bindData(currentPage.value, pageSize.value, searchState.value, searchText.value);
  getListInfo();
})

//通过名称条件查询
function btnSearch() {
  bindData(currentPage.value, pageSize.value, searchState.value, searchText.value)
}

//编辑
const handleEdit = (index, row) => {
  dialogFormVisible.value = true;
  dialogTitle.value = "编辑车位信息";
  formDate.value = row;
}

//删除
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
    `确定要删除车位编号为【${row.Pnumber}】的数据吗?`,
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      icon: markRaw(Delete)//图标
    }
  ).then(() => {
    axios.delete("https://localhost:7090/api/ParkingUseInfo?userid=" + row.Useid + "&pid=" + row.Pid)
      .then((res) => {
        if (res.data) {
          ElMessage({
            type: 'success',
            message: "删除成功",
          })
          bindData(currentPage.value, pageSize.value, searchState.value, searchText.value);
          getListInfo();
        } else {
          ElMessage({
            type: 'error',
            message: "删除失败",
          })
        }
      }).catch((err) => {
        ElMessage({
          message: err,//"网络异常，请联系管理员!!!"
          type: 'error',
        })
      })

  })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '用户取消操作',
      })
    })
}

//添加按钮
function btnAdd() {
  dialogFormVisible.value = true;
  dialogTitle.value = "添加车位信息";
}

//保存
function btnSave(formEl) {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      axios({
        method: formDate.value.Useid == 0 ? "POST" : "PUT",
        url: "https://localhost:7090/api/ParkingUseInfo",
        data: formDate.value,
        headers: { "Content-Type": "application/json" }
      }).then((res) => {
        if (res) {
          ElMessage({
            message: formDate.Useid == 0 ? '添加' : '编辑' + '成功',
            type: 'success',
          })
          getListInfo();
          clearForm();
          bindData(currentPage.value, pageSize.value, searchState.value, searchText.value);
        } else {
          ElMessage({
            message: formDate.Useid == 0 ? '添加' : '编辑' + '失败',
            type: 'error',
          })
        }
      }).catch((err) => {
        ElMessage({
          message: err,//"网络异常，请联系管理员!!!"
          type: 'error',
        })
      })
    } else {
      return false
    }
  })
}


//绑定表格数据
function bindData(page, limit, state, strName) {
  axios.get(`https://localhost:7090/api/ParkingUseInfo?page=${page}&limit=${limit}&state=${state}&strName=${strName}`)
    .then((res) => {
      console.log(res.data);
      tableData.value = res.data.data;
      total.value = res.data.total;
    })
}

//获取下拉列表信息
function getListInfo() {
  //车位
  axios.get(`https://localhost:7090/api/ParkingSpaceInfo/getParkingInfoBindSelect`).then((res) => { parkingList.value = res.data });
  //业主
  axios.get(`https://localhost:7090/api/OwnerInfo/getOwnerInfoBindSelect`).then((res) => { ownerList.value = res.data });
  //车位费用
  axios.get(`https://localhost:7090/api/ParkingPriceInfo/getParkingPriceInfoBindSelect`).then((res) => { parkingPriceList.value = res.data });
}


//关闭模态框
function closeDialog(params) {
  clearForm();
  dialogFormVisible.value = false;
}

//转换日期时间
function convertDateTime(dateStr) {
  if (dateStr != null) {
    var datetimeObj = new Date(dateStr);

    var year = datetimeObj.getFullYear();
    var month = ("0" + (datetimeObj.getMonth() + 1)).slice(-2);
    var day = ("0" + datetimeObj.getDate()).slice(-2);
    var hours = ("0" + datetimeObj.getHours()).slice(-2);
    var minutes = ("0" + datetimeObj.getMinutes()).slice(-2);
    var seconds = ("0" + datetimeObj.getSeconds()).slice(-2);

    var formattedDate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    return formattedDate;
  } else {
    return "";
  }

}

//清理表单
function clearForm() {
  dialogFormVisible.value = false;
  formDate.value = {
    "Useid": 0,
    "Createtime": null,
    "Isdelete": false,
    "Oid": null,
    "Pid": null,
    "Priceid": null,
    "Useendtime": "",
    "Usestarttime": ""
  }
}


//验证
const ruleFormRef = ref();

//表单验证
const rules = reactive({
  Pid: [
    {
      required: true,
      message: '车位编号不能为空',
      trigger: 'change',
    }
  ],
  Oid: [
    {
      required: true,
      message: '车位所有人不能为空',
      trigger: 'change',
    }
  ],
  Priceid: [
    {
      required: true,
      message: '车位价格不能为空',
      trigger: 'change',
    }
  ],
  Usestarttime: [
    {
      required: true,
      message: '开始时间不能为空',
      trigger: 'change',
    }
  ],
  Useendtime: [
    {
      required: true,
      message: '结束时间不能为空',
      trigger: 'change',
    }
  ],
})


</script>